/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.cef.core.validation.lengthvaladaptor;

import com.inspur.edp.cef.api.validation.ICefValidationContext;
import com.inspur.edp.cef.core.i18n.I18nResourceUtil;
import com.inspur.edp.cef.entity.dependenceTemp.DataValidator;
import com.inspur.edp.cef.spi.entity.IAuthFieldValue;
import io.iec.edp.caf.boot.context.CAFContext;

public class AssoLengthValAdaptor extends LengthValAdaptor<Object>
{
	private String foreignKeyName;
	private java.lang.Class assoType;
  private int cefVersion;

  public AssoLengthValAdaptor(String propName, String foreignKeyName, java.lang.Class assoType, int length, int prec)
	{
		super(propName, length, prec);
		DataValidator.checkForEmptyString(foreignKeyName, "foreignKeyName");
		DataValidator.checkForNullReference(assoType, "assoType");

		this.foreignKeyName = foreignKeyName;
		this.assoType = assoType;
	}

  public AssoLengthValAdaptor(String propName, String foreignKeyName, java.lang.Class assoType, int length, int prec,int cefVersion)
  {
    this(propName,foreignKeyName,assoType, length, prec);
    this.cefVersion = cefVersion;

  }

    @Override
    protected
    String getDisplayMessage(ICefValidationContext context) {
        String language= CAFContext.current.getLanguage();
        String exceptionCode=I18nResourceUtil.getResourceItemValue("pfcommon","cef_exception.properties","Gsp_Cef_AssoLen_0001");
        exceptionCode=String.format(exceptionCode,Integer.toString(this.length));
        return exceptionCode;
//        return "关联字段ID长度超过36位，当前长度为"+this.length;
    }

    @Override
	protected boolean isValid(Object value) {
	    //if(length == 0 || value == null){
	    //电科院 兼容
      if(cefVersion==0)
        if(length == 0 || value == null||length == 1){
	        return true;
        }
      else
        {
          if(length==0||value==null)
            return true;
        }
        if(!(value instanceof IAuthFieldValue)){
          return false;
        }
        String AssociationValue = ((IAuthFieldValue) value).getValue();
        return AssociationValue == null || AssociationValue.length() <= length;
    }
}
